﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Media;

namespace WpfApp1.Resources
{
    /* Expander缩进Margin专用转换器 */
    public class ExpanderIndentMarginConverter : IValueConverter
    {
        private readonly int IDENT = 14; // 缩进值

        /// <summary>
        /// 查找指定类型父控件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="child"></param>
        /// <returns></returns>
        private static T FindVisualParent<T>(DependencyObject child) where T : DependencyObject
        {
            DependencyObject parentObject = VisualTreeHelper.GetParent(child);
            if (parentObject == null)
            {
                return null;
            }
                
            T parent = parentObject as T;
            if (parent != null)
            {
                return parent;
            }
            else
            {
                return FindVisualParent<T>(parentObject);
            }
        }

        /// <summary>
        /// 统计指定类型父控件个数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="child"></param>
        /// <returns></returns>
        private static int CountVisualParent<T>(DependencyObject child) where T : DependencyObject
        {
            var node = child;
            int count = 0;
            do
            {
                node = FindVisualParent<T>(node);
                if (node == null)
                {
                    break;
                }

                ++count;
            }
            while (true);

            return count;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            ToggleButton header = value as ToggleButton;
            
            int level = CountVisualParent<Expander>(header); // 取得嵌套等级

            //Console.WriteLine($"{count}");
            return new Thickness((level > 0) ? (level - 1) * IDENT : 0, 0, 0, 0);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
